package com.hsgene.common.util.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * HTTP请求获取信息
 *
 * @Author: wangxuefeng@hsgene.com
 * @Description:
 * @Date: Created in 16:49 2018/6/26
 * @Modified By:
 */
public class HttpUtil {
    /**
     * Log
     */
    private static final Logger LOGGER = LogManager.getLogger(HttpUtil.class);

    /**
     * httpClient
     */
    private static CloseableHttpClient httpClient;

    /**
     * get请求获取
     *
     * @param url 请求地址
     * @return
     */
    public static String doGet(String url) {
        getHttpClient();
        CloseableHttpResponse response = null;
        try {
            LOGGER.info("get request...");
            HttpGet request = new HttpGet(url);
            response = httpClient.execute(request);
            return getHttpRequestResult(response.getStatusLine().getStatusCode(), response.getEntity().getContent());
        } catch (Exception e) {
            LOGGER.error("http get request is error", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                LOGGER.error("close http get is error", e);
            }
        }
        return null;
    }

    private static void getHttpClient() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    /**
     * 处理请求结果的xml格式文件
     *
     * @param code code
     * @param in   in
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    private static String getHttpRequestResult(int code, InputStream in) {
        String result = null;
        //String sendNum = "";
        try {
            if (code == HttpStatus.SC_OK) {
                SAXReader reader = new SAXReader();
                Document doc = reader.read(in);
                //获取根元素
                Element root = doc.getRootElement();
                //Result标签
                result = root.element("Result").getText();
                //sendNum = root.element("SendNum").getText();
            }
        } catch (Exception e) {
            LOGGER.error("http post request is error", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * post请求
     *
     * @param nameValuePairs 参数封装对象
     * @param url            请求地址
     * @param charset        编码格式
     * @return
     */
    public static String doPost(List<NameValuePair> nameValuePairs, String url, String charset) {
        getHttpClient();
        String result = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost post = new HttpPost(url);
            HttpEntity entity = new UrlEncodedFormEntity(nameValuePairs);
            //将发送消息的载体对象封装到httppost对象中
            post.setEntity(entity);
            response = httpClient.execute(post);
            result = EntityUtils.toString(response.getEntity(), charset);
            System.out.println("post请求结果：" + result);
            return result;
        } catch (Exception e) {
            LOGGER.error("post request query is error...", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (Exception e) {
                LOGGER.error("close http post is error", e);
            }
        }
        return result;
    }

}
